<?php


namespace app\index\controller;

use app\index\model\OrderItem;
use app\index\model\PurchaseDetail;
use app\index\model\Vendor;
use app\index\model\Product;
use app\index\model\Purchase;
use app\index\model\StockWarehouse;
use app\index\model\User;
use think\Loader;
use think\Request;
use think\response\Json;

class PurchaseController extends BaseController
{

    protected $request;
    protected $validate;
    protected $vendorValidate;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=$request;
        $this->validate=Loader::validate('Purchase');
        $this->vendorValidate=Loader::validate('Vendor');
    }

    public function getParam()
    {
        ['status'=>$status,'result'=>$result]=StockWarehouse::getStockWarehouseList($this->user_session['group_id']);
        ['user_list'=>$user_list,'group_list'=>$group_list]=User::getUserList();
        $vendor_list = Vendor::getVendorCompanyNameList();
        return json(['code'=>0,'stock_warehouse'=>$result['stock_warehouse'],'user_list'=>$user_list,'group_list'=>$group_list, 'vendor_list'=>$vendor_list]);
    }

    /**
     * 获取采购列表
     * create by yhb on 2021/3/9 15:51
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getList(){
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'stock_warehouse'=>$post['warehouse']??null,
            'create_time'=>$post['create_time']??null,
            'vendor_list'=>$post['vendor_list']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];

        $purchase = new Product();
        ['status'=>$status,'result'=>$result]=$purchase->getPurchaseList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'product'=>$result['product'],'pageTotal'=>$result['total']]);
    }

    /**
     * 通过Ids获取该条信息
     * create by yhb on 2021/4/1 17:32
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductByIds()
    {
        $id=input('post.id/a');
        if(!$id){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }
        $productIds = [];
        $vendorIds = [];
        foreach($id as $key=>$val){
            $productIds[] = $val['id'];
            $vendorIds[] = $val['vendor_id'];
        }
        $purchase = new Product();
        ['status'=>$status,'result'=>$result]=$purchase->getProductByIds($productIds,$vendorIds);

        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data']]);

    }

    /**
     * 通过Id获取该条信息
     * create by yhb on 2021/4/1 17:32
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductById()
    {
        $id=input('post.id');
        $productId['id'] = $id;
        if(!$id){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }
        $purchase = new Product();
        ['status'=>$status,'result'=>$result]=$purchase->getProductById($productId);

        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data']]);
    }

    /**
     * 执行添加或修改操作
     * create by yhb on 2021/3/10 17:55
     * @return \think\response\Json
     */
    public function addPurchase()
    {
        $data = input('post.data/a');
        $purchase = new Purchase();

        $purchaseId = $purchase::generatePurchaserId();
        $insert_purchase = [];
        $insert_purchase_detail = [];
        $update_product = [];
        foreach ($data as $k=>$v){
            if(empty($v['purchase_number'])){
                return json(['code'=>1,'msg'=>'请输入需要购买的数量']);
            }
            $v['purchase_id'] = "PUR".$purchaseId;
            $insert_purchase = [
                'purchase_id' => $v['purchase_id'],
                'remark' => $v['remark']??'',
                'type' => 0,
                'create_user'=>$this->user_session['id'],
            ];

            $insert_purchase_detail[] = [
                'pro_id'=>$v['id'],
                'en_name' => $v['en_name'],
                'cn_name' => $v['cn_name'],
                'amount' => $v['purchase_number'],
                'pur_price' => $v['pur_price'],
                'remark' => $v['remark']??'',
                'image' => $v['image'],
                'priority' => $v['priority'],
                'vendor_id' => $v['vendor_id'],
                'warehouse' => $v['warehouse'],
                'type' => $v['type'],
                'create_user'=>$this->user_session['id'],
            ];

            $update_product[] =[
                'in_transit_stock' => $v['in_transit_stock']+$v['purchase_number'],
                'id' => $v['id'],
            ];
        }

        ['status'=>$status,'result'=>$result]=$purchase->addPurchase($insert_purchase,$insert_purchase_detail,$update_product);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * 添加采购新品和新的供应商
     * create by yhb on 2021/3/13 9:21
     * @return Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function newPurchase()
    {
        $data=input('post.data/a');
        $purchase_validate = new \app\index\validate\Purchase();
        $validate_result=$purchase_validate->scene('create')->check($data);

        if(!$validate_result){
            return json(['code'=>1,'msg'=>$purchase_validate->getError()],200);
        }
        if(is_int($data['company'])){
            $vendor_data = [
                'id' => $data['company'],
                'telephone' => $data['telephone'],
                'address' => $data['address'],
            ];
        }else {
            $vendor_data = [
                'company' => trim($data['company']),
                'telephone' => $data['telephone'],
                'address' => $data['address'],
            ];
        }
        $purchase_data=[
            'cn_name'=>trim($data['cn_name']),
            'en_name'=>trim($data['en_name']),
            'image'=>$data['image'],
            'pur_price'=>$data['pur_price'],
            'amount'=>$data['amount'],
            'weight'=>$data['weight']??null,
            'warehouse'=>$data['warehouse'],
            'type'=>$data['type'],
            'create_user'=>$this->user_session['id'],
        ];

        ['status'=>$status,'result'=>$result]=Purchase::addNewPurchase($purchase_data,$vendor_data);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function getNewPurchaseParam()
    {
        ['status'=>$status,'result'=>$result]=StockWarehouse::getStockWarehouseList($this->user_session['group_id']);
//        ['vendor_list'=>$vendor_list]=$vendorClass->getVendorName();
        $type_list=Purchase::$type_list;
        $vendor_list = Vendor::getVendorCompanyNameList();
        return json(['code'=>0,'stock_warehouse'=>$result['stock_warehouse'],'vendor_list'=>$vendor_list,'type_list'=>$type_list]);
    }

    /**
     * getPurchasedParam
     *
     * @url purchase/purchased/Param
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/3/11
     */
    public function purchasedParam(): Json
    {
        ['purchase_status'=>$purchase_status,'ship_status'=>$ship_status,'stock_status'=>$stock_status,'type_list'=>$type_list,'priority_list'=>$priority_list]=PurchaseDetail::getPurchasedParam();
        return json(['code'=>0,'purchase_status'=>$purchase_status,'ship_status'=>$ship_status,'stock_status'=>$stock_status,'type_list'=>$type_list,'priority_list'=>$priority_list]);
    }

    /**
     * getPurchasedList
     * 已建采购单列表
     * @url purchase/purchased/list
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/3/11
     */
    public function purchasedList(): Json
    {
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'stock_status'=>$post['stock_status']??null,
            'ship_status'=>$post['ship_status']??null,
            'vendor'=>$post['vendor']??null,
            'purchase_status'=>$post['purchase_status']??null,
            'create_time'=>$post['create_time']??null,
            'type'=>$post['type']??null,
            'priority'=>$post['priority']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=PurchaseDetail::getPurchasedList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        $vendor_list=Vendor::getVendorCompanyNameList();
        return json(['code'=>0,'data'=>$result['data'],'pageTotal'=>$result['total'],'vendor_list'=>$vendor_list]);
    }

    /**
     * purchaseUpdateStatus
     * 更新采购信息
     * @url purchase/purchased/submit
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/3/11
     */
    public function purchaseUpdateStatus(): Json
    {
        $data=input('post.');
        $id=$data['id'];
        $update=[
            'real_pur_amount'=>$data['amount'],
            'real_pur_price'=>$data['pur_price'],
            'waybill_no'=>$data['waybill_no'],
            'vendor_id'=>$data['vendor'],
            'remark'=>$data['remark'],
        ];
        ['status'=>$status,'result'=>$result]=PurchaseDetail::purchaseUpdateStatus($id,$update);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function addRemark(){
        $remark=input('post.remark');
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=PurchaseDetail::purchaseAddRemark($id,$remark);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * purchaseUpdateUnable
     * 无法采购
     * @url purchase/purchased/unable
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/3/11
     */
    public function purchaseUpdateUnable(): Json
    {
        $remark=input('post.remark');
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=PurchaseDetail::purchaseUpdateUnable($id,$remark);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * purchaseReceipt
     * 更新采购单到货
     * @url purchase/purchased/receipt
     * @method POST
     * @return Json
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/3/11
     */
    public function purchaseReceipt(): Json
    {
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=PurchaseDetail::purchaseReceipt($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * updateWaybillBatch
     * 更新物流单号
     * @url
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/3/11
     */
    public function updateWaybillBatch(): Json
    {
        $ids=input('post.ids/a');
        $waybill_no=input('post.waybill');
        ['status'=>$status,'result'=>$result]=PurchaseDetail::updateWaybillBatch($ids,$waybill_no);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function confirmParam(){
        ['status'=>$status,'result'=>$result]=StockWarehouse::getStockWarehouseList($this->user_session['group_id']);
        $vendorList = Vendor::getVendorCompanyNameList();

        return json(['code'=>0,'warehouse_list'=>$result['stock_warehouse'],'vendor_list'=>$vendorList]);
    }

    public function confirmList(){
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=PurchaseDetail::getConfirmList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'data'=>$result['data'],'pageTotal'=>$result['total']]);
    }

    public function stockIn(){
        $data=input('post.');
        $id=$data['id'];
        $validate_result=$this->validate->scene('stock_in')->check($data);
        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }
        if($data['pro_id']){
            $update=[
                'pur_price'=>$data['pur_price'],
                'amount'=>$data['amount'],
                'image'=>$data['image'],
                'vendor_id'=>$data['company'],
                'pro_id'=>$data['pro_id'],
                'selling_price'=>$data['selling_price'],
                'create_user'=>$this->user_session['id'],
            ];
            ['status'=>$status,'result'=>$result]=PurchaseDetail::stockIn($update,$id);
            if($status===false){
                return json(['code'=>1,'msg'=>$result]);
            }
            ['status'=>$status,'result'=>$stockResult]=Product::lockStockByProduct($data['pro_id']);
            if($status===false){
                return json(['code'=>2,'msg'=>'更新库存成功，锁定库存失败',$stockResult]);
            }
            ['status'=>$status,'result'=>$stockResult]=Product::demandStockByProduct([$data['pro_id']]);
            if($status===false){
                return json(['code'=>2,'msg'=>'更新库存成功，锁定需求库存失败',$stockResult]);
            }
        }else{
            $insert=[
                'cn_name'=>trim($data['cn_name']),
                'en_name'=>trim($data['en_name']),
                'pur_price'=>$data['pur_price'],
                'image'=>$data['image'],
                'vendor_id'=>$data['company'],
                'type'=>$data['type'],
                'amount'=>$data['amount'],
                'weight'=>$data['weight'],
                'warehouse'=>$data['warehouse'],
                'selling_price'=>$data['selling_price'],
                'create_user'=>$this->user_session['id'],
            ];
            ['status'=>$status,'result'=>$result]=PurchaseDetail::createProduct($insert,$id);
        }
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>'入库成功','pro_id'=>$result['pro_id']]);
    }

    public function stockInById(){
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=PurchaseDetail::stockInById($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        ['status'=>$status,'result'=>$stockResult]=Product::lockStockByProduct($result['pro_id']);
        if($status===false){
            return json(['code'=>2,'msg'=>'更新库存成功，锁定库存失败',$stockResult]);
        }
        ['status'=>$status,'result'=>$stockResult]=Product::demandStockByProduct([$result['pro_id']]);
        if($status===false){
            return json(['code'=>2,'msg'=>'更新库存成功，锁定需求库存失败',$stockResult]);
        }
        return json(['code'=>0,'msg'=>'入库成功']);
    }

    public function endPurchase(){
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=PurchaseDetail::endPurchase($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>'已完结']);
    }

    /**
     * 供应商搜索条件
     * create by yhb on 2021/3/23 14:02
     * @return Json
     */
    public function getVendorParam()
    {
        $vendor_list = Vendor::getVendorCompanyNameList();
        return json(['code'=>0, 'vendor_list'=>$vendor_list]);
    }

    /**
     * 获取供应商列表
     * create by yhb on 2021/3/23 16:46
     * @return Json
     */
    public function getVendorList()
    {
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'vendor_list'=>$post['vendor_list']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];

        $vendorClass = new Vendor();
        ['status'=>$status,'result'=>$result]=$vendorClass->getVendorList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'vendor'=>$result['vendor'],'pageTotal'=>$result['total']]);
    }

    /**
     * 添加供应商
     * create by yhb on 2021/3/23 16:47
     * @return Json
     */
    public function addVendor()
    {
        $data = input('post.data/a');
        $vendorClass = new Vendor();

        if (!$this->vendorValidate->scene('create')->check($data)) {
            return json(['code' => 1, 'msg' =>$this->vendorValidate->getError()], 200);
        }
        $insert_data = [
            'company'=>$data['company'],
            'name'=>$data['name'],
            'address'=>$data['address'],
            'wechat'=>$data['wechat'],
            'telephone'=>$data['telephone'],
            'web'=>$data['web'],
            'remark'=>$data['remark'],
        ];
        ['status' => $status, 'result' => $result] = $vendorClass->addVendor($insert_data);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code' => 0, 'msg' => $result]);
    }

    /**
     * 隐藏商品
     * create by yhb on 2021/3/26 14:04
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hideProduct()
    {
        $product_id = input('post.id');

        $productClass = new Product();

        ['status'=>$status,'result'=>$result]=$productClass->hideProduct(['id'=>$product_id]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * 获取需求库存详情列表
     * create by yhb on 2021/3/29 10:21
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPurchaseList()
    {
        $id = input('post.id');

        $productClass = new OrderItem();
        ['status'=>$status,'result'=>$result]=$productClass->getProductStockList($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'stockList'=>$result['data']]);
    }

    /**
     * 获取ids相对性供应商信息
     * create by yhb on 2021/3/31 15:01
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductAll()
    {
        $id=input('post.id/a');
        if(!$id){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }
        $purchase = new Product();
        ['status'=>$status,'result'=>$result]=$purchase->getProductAll($id);

        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data']]);
    }

    /**
     * 批量添加新品采购
     * create by yhb on 2021/3/31 18:40
     * @return Json
     */
    public function insertBatchPurchase()
    {
        $data = input('post.data/a');
        $validate_result=$this->validate->scene('create_batch_purchase')->check($data);
        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }

        $purchaseId = Purchase::generatePurchaserId();
        if(!empty($data)){
            foreach ($data['purchase'] as $k=>$v){
                $v['purchase_id'] = "PUR".$purchaseId;
                $insert_purchase = [
                    'purchase_id' => $v['purchase_id'],
                    'type' => $data['type']??1,
                    'create_user'=>$this->user_session['id'],
                ];

                $insert_purchase_detail[] = [
                    'en_name' => $v['en_name'],
                    'cn_name' => $v['cn_name'],
                    'amount' => $v['amount'],
                    'weight' => $v['weight']?null:$v['weight'],
                    'priority'=>$v['priority'],
                    'pur_price' => $v['pur_price'],
                    'remark' => $v['remark'],
                    'image' => $v['image'],
                    'warehouse' => $data['warehouse'],
                    'type' => $v['type'],
                    'create_user'=>$this->user_session['id'],
                ];

            }
        }else{
            return json(['code'=>1,'msg'=>'请填写需要采购的新品']);
        }
        ['status'=>$status,'result'=>$result] = Purchase::insertBatchPurchase($insert_purchase,$insert_purchase_detail,$data['company']);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);

    }

    /**
     * 通过ids获取同一供应商下的采购详情列表
     * create by yhb on 2021/4/2 16:58
     * @return Json
     */
    public function getPurchasedByIds()
    {
        $id=input('post.id/a');
        $purchaseDetailIds = [];
        $vendorIds = [];
        foreach($id as $key=>$val){
            $purchaseDetailIds[] = $val['id'];
            $vendorIds[] = $val['vendor_id'];
        }
        $purchaseDetail = new PurchaseDetail();
        ['status'=>$status,'result'=>$result]=$purchaseDetail->getPurchaseDetailByIds($purchaseDetailIds,$vendorIds);

        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'data'=>$result['data']]);
    }

    /**
     * 执行批量修改运单
     * create by yhb on 2021/4/2 16:59
     * @return Json
     */
    public function updatePurchaseDetail()
    {
        $data = input('post.data/a');
        $purchaseDetail = new PurchaseDetail();
        $validate_result=$this->validate->scene('create_batch_purchase_detail')->check($data);
        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }

        ['status'=>$status,'result'=>$result] = $purchaseDetail->updatePurchaseDetail($data);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * 批量到货
     * create by yhb on 2021/4/6 15:46
     * @return Json
     * @throws \think\exception\PDOException
     */
    public function updateBatchDelivery()
    {
        $id=input('post.id/a');
        $purchaseDetailClass = new PurchaseDetail();
        ['status'=>$status,'result'=>$result]=$purchaseDetailClass->updateBatchDelivery($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

}